package com.shengwei.truck.driver.view.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.lifecycle.Observer;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskDetailData;
import com.shengwei.truck.driver.bean.task.TaskItem;
import com.shengwei.truck.driver.databinding.ActivityQrcodeBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.task.TaskDetailActivity;
import com.shengwei.truck.driver.vm.TaskDetailViewModel;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/***
 * 首页点击“二维码”，进入的二维码页面
 */
public class QrcodeActivity extends BaseActivity<TaskDetailViewModel, ActivityQrcodeBinding> implements View.OnClickListener {
    private String mCurTaskId;
    private Disposable mDisposable;
    private long mLeftTime;
    private String TAG = "QrcodeActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.setFinishOnTouchOutside(false);
        super.onCreate(savedInstanceState);
        initView();
        initLiveDataObersve();
        getLastIntent();
        if(mCurTaskId != null) {
            mViewModel.getTaskDetail(mCurTaskId);
        }
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {
        //监听获取任务详情的数据
        mViewModel.getTaskDetailLiveData().observe(this, new Observer<Result<JsonTaskDetailData>>() {
            @Override
            public void onChanged(Result<JsonTaskDetailData> result) {
                result.handler(new OnCallback<JsonTaskDetailData>() {
                    @Override
                    public void onSuccess(JsonTaskDetailData data) {
                        //加载二维码图片
                        RequestOptions requestOptions = new RequestOptions();
                        requestOptions.error(R.drawable.bg_qrcode);
                        String qrCodeUrl = data.qrCodeUrl;
                        Glide.with(getApplicationContext()).load(qrCodeUrl).apply(requestOptions).into( mDataBinding.imvQrcode);
                        mLeftTime = data.lastTime;
                        String strLeftTime = getLeftTimeStr(mLeftTime);
                        if(!TextUtils.isEmpty(strLeftTime))
                            mDataBinding.tvLeftTime.setText(strLeftTime);
                        startTimeDown();
                    }
                });
            }
        });

        //监听接  “提货”  接口的数据
        mViewModel.getRecvTaskLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        //模拟修改成功
                        String tip = QrcodeActivity.this.getResources().getString(R.string.qr_has_get_goods);
                        MyToast.showToastCenter(new WeakReference<>(QrcodeActivity.this),tip,Toast.LENGTH_SHORT,true);
                        finish();
                    }
                    @Override
                    public void onError(Throwable throwable) {
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });
            }
        });
    }

    /**
     * 将剩余时间毫秒值 转为 hh:mm:ss
     * @param leftMillsTime
     * @return
     */
    public String getLeftTimeStr(long leftMillsTime){
        String strLeftTime;
        if(mLeftTime > 0){
            strLeftTime = DateTimeUtils.getGapTime(mLeftTime);
       }
       else{
            strLeftTime = QrcodeActivity.this.getResources().getString(R.string.has_due);
       }
       return strLeftTime;
    }

    /**
     * 开始倒计时，每隔1秒后执行
     */
    public void startTimeDown() {
         mDisposable =  Observable.interval(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        MyLogCat.i(TAG,String.valueOf(aLong));
                        mLeftTime -= 1000;
                        String strLeftTime = getLeftTimeStr(mLeftTime);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mDataBinding.tvLeftTime.setText(strLeftTime);
                            }
                        });
                    }
                });
    }

    @Override
    protected void onStop() {
        if(mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        super.onStop();
    }

    /**
     * 获取上一页传递来的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            TaskItem curTaskItem = bundle.getParcelable("taskItem");
            if(curTaskItem != null) {
                mCurTaskId = curTaskItem.id;
                mDataBinding.setTaskItem(curTaskItem);
            }
        }
    }

    private void initView() {
        setActivityDimen();
        mDataBinding.btCloseDialog.setOnClickListener(this);
        mDataBinding.btTaskDetail.setOnClickListener(this);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_qrcode;
    }
    /**
     * 设置Activity宽高
     */
    public void setActivityDimen() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = (int) getResources().getDimension(R.dimen.activity_dialog_width);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btCloseDialog:
                //模拟将状态改为已提货,其实和“接受任务”用的是同一个接口，只是状态值传2
                mViewModel.recvTaskDetail(mCurTaskId,2);

                break;
            case R.id.btTaskDetail:
                if(TextUtils.isEmpty(mCurTaskId)) {
                    Toast.makeText(QrcodeActivity.this,R.string.task_id_not_empty,Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent i = new Intent(this, TaskDetailActivity.class);
                i.putExtra("id",mCurTaskId);
                startActivity(i);
                break;
        }
    }
}